import axios from 'axios';
import md5 from '@/utils/md5';
import { env } from '@/api/root';
const SelfConfig = require('../config');
const ApiCnfig = require('./apiConfig');

const User = SelfConfig.user;
const Version = SelfConfig.version;
const TradeId = SelfConfig.tradeId;
const TradeInsideArr = SelfConfig.tradeInsideArr;
const TradeOutsideArr = SelfConfig.tradeOutsideArr;

axios.defaults.timeout = 60000;

const service = axios.create({});

// 请求拦截,设置统一header
service.interceptors.request.use(
  (config) => {
    config.headers['content-Type'] = 'application/json; charset=UTF-8';

    if (config.url.indexOf('.jsp') >= 0) return config;
    if (config.url.indexOf('/yl1001') >= 0) return config;
    let url = config.data.url || config.url;
    let user = url.match(/user=([^&]+)/) && url.match(/user=([^&]+)/)[1];
    let func = url.match(/func=([^&]+)/) && url.match(/func=([^&]+)/)[1];
    let userItem = User.find((ele) => ele.prev === user);
    let tradeItem = TradeInsideArr.find((ele) => ele.name === func);
    if (userItem) {
      url = url.replace(`user=${userItem.prev}`, `user=${userItem.cur}`);
      if (Version) url = url.replace(/version=([^&]+)/, `version=${Version}`);
      if (config.data.url) {
        config.data.url = url;
      } else {
        config.url = url;
      }
    }
    if (tradeItem) {
      let condition = config.data[tradeItem.prop]
        ? JSON.parse(config.data[tradeItem.prop])
        : {};
      condition.tradeid = TradeId;
      config.data[tradeItem.prop] = JSON.stringify(condition);
    }
    if (TradeOutsideArr.indexOf(func) >= 0) {
      config.data.tradeid = TradeId;
    }
    if (TradeId) {
      config.headers['tradeid'] = TradeId;
    }
    if (env == 'local') {
      config.headers['n-d-version'] =
        ' {"yl1001-boot-career-report":"1.9","yl1001-boot-occupation-platform":"1.9","yl1001-boot-yp":"1.9","yl1001-boot-pay-platform":"1.9"}';
    }
    return config;
  },
  (err) => {
    return Promise.resolve(err);
  }
);
// 如果切换了网络就会返回空的响应，所以结合切换网络字段处理
function handleSwitchNetworkEmptyResponse(response) {
  const isNetworkChanged = uni.getStorageSync('isNetworkChanged1');
  if (!response.status && isNetworkChanged) {
    uni.removeStorageSync('isNetworkChanged');
    const app = getApp() || uni.getApp();
    console.log('app', app.showNetworkLostModal);

    app.showNetworkLostModal();
  }
}
//  响应拦截
service.interceptors.response.use(
  (res) => {
    return Promise.resolve(res.data);
  },
  (err) => {
    // handleSwitchNetworkEmptyResponse(err.response);
    if (process.env.NODE_ENV === 'production') console.error('axios', err);
    uni.showToast({ icon: 'none', title: err, duration: 2000 });
    // uni.showToast({ icon: "none", title: "服务器异常" });
    return Promise.reject(err);
  }
);

service.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    var settle = require('axios/lib/core/settle');
    var buildURL = require('axios/lib/helpers/buildURL');
    uni.request({
      method: config.method.toUpperCase(),
      url: buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data && JSON.parse(config.data),
      params: config.params,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete(res) {
        let response = {
          data: res.data,
          status: res.statusCode,
          errMsg: res.errMsg,
          header: res.header,
          config: config
        };
        settle(resolve, reject, response);
      },
      fail(err) {
        if (process.env.NODE_ENV === 'production') {
          console.error('uni.request', err);
          console.error('config', config);
        }
        uni.showToast({ icon: 'none', title: '服务器异常', duration: 2000 });
      }
    });
  });
};

let request1 = {
  get: function (url, params = {}) {
    return new Promise((resolve, reject) => {
      service
        .get(url, {
          params: params
        })
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      service
        .post(url, data)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  handleEntropy: function (url, personid = '') {
    const time = +new Date(); //时间戳
    const key = '1qaz2wsx1001';
    const cks = md5(md5(personid + time) + key);
    const newUrl = `${url}?personid=${personid}&time=${time}&cks=${cks}`;
    return newUrl;
    // if (process.env.NODE_ENV === "development") {
    //   const time = +new Date(); //时间戳
    //   const personid = "1";
    //   const key = "1qaz2wsx1001";
    //   const cks = md5(md5(personid + time) + key);
    //   const newUrl = `${url}?personid=${personid}&time=${time}&cks=${cks}`;
    //   return newUrl;
    // } else {
    //   return `${url}?personid=i&time=1654659719450&cks=ca8f7c96bfbcafa4e72f90f95c0bdc64`;
    // }
  },

  // apiPre：接口前缀；
  // configName：相应提供商，对应文件ApiConfig；
  // apiPath: 格式是 /{version}/{class}/function；
  // data：接口数据
  // 调用例子：request.webservice(apiYL, 'mp', '/rightOpen/getCompanyPersonAll', data);
  webservice: function (apiPre, configName, apiPath, data) {
    return new Promise((resolve, reject) => {
      var configObj = ApiCnfig[configName];
      var { realm, authorization } = getRealmAndAuthorization(
        configObj,
        apiPre,
        apiPath
      );
      var url = apiPre + apiPath;
      service
        .post(url, data, {
          headers: {
            realm: realm,
            authorization: authorization
          }
        })
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
};

export default request1;
